package com.woniu.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * projectName: demo_box
 *
 * @author: 蔡百强
 * time: 2024/4/16 23:15 周二
 * description:
 */
@RestController
public class FileUploadController {

//    @Value("${upload.path}")
//    private String uploadPath;

    @PostMapping("/upload/")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择要上传的文件", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 定义存储路径
            File uploadDir = new File("/path/to/upload/directory");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 保存文件
            file.transferTo(new File(uploadDir, fileName));
            return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}